#include <sys/types.h>
#include <syscall.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/resource.h>
#include <sys/times.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sched.h>
#include <time.h>
#include <sys/wait.h>
#include <sys/syscall.h>

double get_current_time() {
  struct timespec ts;
  syscall(__NR_clock_gettime, CLOCK_REALTIME, &ts);
  return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; 
}

int main(int argc, char** argv) {
  int migrations = atoi(argv[1]);
  pid_t my_pid = getpid();
  printf("pid %d\n", my_pid);
  double start_time = get_current_time();
  cpu_set_t cpu_set;
  for (int i = 0; i < migrations; i++) {
    CPU_ZERO(&cpu_set);
    CPU_SET(i % 2, &cpu_set);
    sched_setaffinity(my_pid, sizeof(cpu_set), &cpu_set);
    //    get_current_time();
  }
  double elapsed_time = get_current_time() - start_time;
  printf("time taken %.5f for %d migrations, %.5fus per migration\n", 
         elapsed_time, migrations, elapsed_time * 1000000.0 / (double)migrations);
  start_time = get_current_time();
  for (int i = 0; i < migrations; i++) {
    CPU_ZERO(&cpu_set);
    CPU_SET(i % 2, &cpu_set);
  }
  printf("time taken %.5f for no migrations\n", get_current_time() - start_time);
}

